#!/usr/bin/python
# -*- coding: UTF-8 -*-
 

import os
import sys
cur_path =os.path.abspath(os.path.join(os.path.dirname('__file__'), os.path.pardir))
sys.path.append(cur_path)

from psm_conf import *

import socket
gHostname = socket.gethostname() # 获取本地主机名
gLocalIp=socket.gethostbyname(socket.getfqdn(gHostname))


import json
from kazoo.client import KazooClient
import time

import thrift


from controller_src import ps_moniter_controller
from controller_src.ttypes import *

from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer
from kazoo.client import KazooClient

from worker.worker_src import ps_moniter_worker
from worker.worker_src.ttypes import *
from worker.worker_src.constants import *
from hulk_proxy.HulkProxyServ import Client
from scan_data.ttypes import ScanData



def getPsmInfo(machine_type):
    info={}
    timeout = 100
    zkc = KazooClient(hosts=zkUrl, timeout=timeout)
    zkc.start()
    if not zkc.exists(zkPath+"/"+machine_type):
        print(zkPath+"/"+machine_type+"不存在")
        return info
    children=zkc.get_children(zkPath+"/"+machine_type)

    tsocket = TSocket.TSocket(hulk_host, hulk_port)
    transport = TTransport.TFramedTransport(tsocket)
    protocol = TBinaryProtocol.TBinaryProtocol(transport)
    client = Client(protocol)
    transport.open()
    for child in children:
        tmp_hash = "psm_"+child
        ret = client.hget(tmp_hash, "ps_number")
        if not ret:
            continue # zk在线，hulk没数据，不可能的情况
        info[tmp_hash]=int(ret)
    transport.close()
    return info



machine_types=["realtime", "offline", "online"]

while True:
    for machine_type in machine_types:
        # 获取线上worker信息
        psmInfo = getPsmInfo(machine_type)
        if not psmInfo:
            print("no %s psm_worker"%machine_type)
            continue
        for worker_address_info, v in psmInfo.items():
            print(worker_address_info)
            ip_port = worker_address_info.split('_')[1].split(':') #psm_127.127.127.127:12345
            transport = TSocket.TSocket(ip_port[0], int(ip_port[1]))
            transport = TTransport.TBufferedTransport(transport)
            protocol = TBinaryProtocol.TBinaryProtocol(transport)
            client = ps_moniter_worker.Client(protocol)
            # Connect!
            transport.open()
            ret = client.pwd()
            transport.close()
    time.sleep(10)

